package cn.itrip.search.dao;

import cn.itrip.common.Page;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.List;
public class SolrBaseDao<T> {
    //通过这个对象向solr发送http请求，拿到相关数据
    private HttpSolrClient solrClient;


    //这个对象， 将solr返回的数据接收过来
    private QueryResponse queryResponse;

    /**
     * 重载构造，赋初始值
     */
    public SolrBaseDao(String url){
        solrClient = new HttpSolrClient(url);
        solrClient.setParser(new XMLResponseParser());
        //设置转换器，默认返回值为Xml
        solrClient.setConnectionTimeout(500000);

    }

    /**
     * 查询全部数据
     *
     * solrQuery
     * //通过这个类的对象设置具体需要的查询参数，然后把这个对象放入HttpSolrClient
     *
     */
    public List<T> getAllList(SolrQuery solrQuery,Class clazz) throws IOException, SolrServerException {
        //实例化返回给服务端数据的对象
        queryResponse =solrClient.query(solrQuery);
        List<T> list = queryResponse.getBeans(clazz);
        return  list;
    }


    /**
     * 分页查询数据
     * 数据存入page分页对象中
     */
    public Page<T> getLimitPage(SolrQuery solrQuery,int currNo,int pageSize,Class clazz) throws  Exception{

        //实例化返回给服务端数据的对象
        queryResponse =solrClient.query(solrQuery);
        List<T> list = queryResponse.getBeans(clazz);
        SolrDocumentList solrDocumentList=queryResponse.getResults();

        //创建私有page传参
        Page<T> page = new Page<>(currNo,pageSize,(int)solrDocumentList.getNumFound());
        page.setRows(list);
        return page;
    }



}
